package cn.ailanyin.home.filters;

import cn.ailanyin.home.common.context.UserInfoContext;
import cn.ailanyin.home.common.utils.JwtUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 用户信息过滤器
 *
 * @author ailanyin
 * @date 2023-09-16 21:22:13
 */
@Component
@Order(2)
@RequiredArgsConstructor
public class UserInfoFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        try {
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            // 获取Token
            String token = JwtUtil.getToken(request, true);
            if (StrUtil.isNotBlank(token)) {
                // 设置userId
                UserInfoContext.setUserId(getUserId(token));
                // 设置username
                UserInfoContext.setUsername(getUsername(token));
                // 设置HomeId
                UserInfoContext.setHomeId(getHomeId(token));
                // 设置用户姓名
                UserInfoContext.setNickname(getNickname(token));
            }

            // 放行
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            UserInfoContext.clear();
        }
    }

    private String getUserId(String token) {
        try {
            return JwtUtil.parseToken(token).getPayload(JwtUtil.PAYLOAD_USER_ID).toString();
        } catch (Exception e) {
            return null;
        }
    }

    private String getUsername(String token) {
        try {
            return JwtUtil.parseToken(token).getPayload(JwtUtil.PAYLOAD_USERNAME).toString();
        } catch (Exception e) {
            return null;
        }
    }

    private String getHomeId(String token) {
        try {
            return JwtUtil.parseToken(token).getPayload(JwtUtil.PAYLOAD_HOME_ID).toString();
        } catch (Exception e) {
            return null;
        }
    }

    private String getNickname(String token) {
        try {
            return JwtUtil.parseToken(token).getPayload(JwtUtil.PAYLOAD_NICKNAME).toString();
        } catch (Exception e) {
            return null;
        }
    }

}
